<template>
  <div :id="chartId" class="chart-area"></div>
</template>

<script>
import Chart from "chart.js";

export default {
  name: "pie-chart",
  props: {
    chartId: {
      type: String,
      default: "pie-chart",
    },
    chartData: {
      type: Object,
      default: () => {
        return {
          labels: [],
          datasets: [
            {
              label: "Data",
              backgroundColor: [],
              data: [],
            },
          ],
        };
      },
    },
    extraOptions: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      let ctx = document.getElementById(this.chartId).getContext("2d");

      if (this.chart) {
        this.chart.destroy();
      }

      let defaultOptions = {
        responsive: true,
        maintainAspectRatio: false,
        legend: {
          position: "right",
        },
      };

      let options = {
        ...defaultOptions,
        ...this.extraOptions,
      };

      this.chart = new Chart(ctx, {
        type: "pie",
        data: this.chartData,
        options: options,
      });
    },
  },
  watch: {
    chartData: {
      handler() {
        this.renderChart();
      },
      deep: true,
    },
  },
};
</script>

<style>
.chart-area {
  height: 100%;
  width: 100%;
}
</style>